package cn.stylefeng.guns.modular.demo.utils;

import cn.hutool.core.util.RandomUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.http.HttpHeaders;

import javax.servlet.http.HttpServletResponse;

/**
 * 文件上传工具类
 */
public class FileUtil {

    /**
     * 文件上传
     * @param file
     * @param SaveServerPath
     * @param modulesPath
     */
    public static Map<String, Object> upload(MultipartFile file, String SaveServerPath, String modulesPath){
        SimpleDateFormat formatter= new SimpleDateFormat("yyyyMMdd");
        Date date = new Date(System.currentTimeMillis());
        String format = formatter.format(date);
        modulesPath = "/uploadfile/"+format+"/"+modulesPath;
        Map<String, Object> res = new LinkedHashMap<>();
        String originalFilename = file.getOriginalFilename();
        String fileName = originalFilename.substring(0, originalFilename.lastIndexOf("."));
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String saveFilename = RandomUtil.randomString(16)+suffixName;

        res.put("file_name", fileName);
        res.put("file_type", suffixName);
        res.put("file_size", file.getSize() / 1024 + "K");
        try {
            String file_path = SaveServerPath + modulesPath+"/"+ saveFilename;
            File uploadFile = new File(file_path);
            if (!uploadFile.getParentFile().exists()) {
                uploadFile.getParentFile().mkdirs();
            }
            file.transferTo(uploadFile);
            res.put("file_path",file_path);
            res.put("name",saveFilename);
            res.put("url",modulesPath + "/" + saveFilename);

            System.out.println(res);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }



    @GetMapping("/download")
    public void downloadFile(HttpServletResponse response) {
        String filePath = "/path/to/file.txt";
        File file = new File(filePath);

        try {
            InputStream inputStream = new FileInputStream(file);
            OutputStream outputStream = response.getOutputStream();

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            String fileName = file.getName();
            String contentType = "application/octet-stream";
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.setContentType(contentType);

            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件下载
     * @param url
     * @param saveFileName
     * @return
     */
    public static ResponseEntity<byte[]> down(String url, String saveFileName){
        try {
            File file=new File(url);
            HttpHeaders headers = new HttpHeaders();
            String downloadFileName = new String(saveFileName.getBytes("UTF-8"),"iso-8859-1");
            headers.setContentDispositionFormData("attachment", downloadFileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取单元格的内容
     * @param cell
     * @return
     */
    public static String getCellValue(Cell cell) {
        // 判断是否为null或空串
        if (cell == null || cell.toString().trim().equals("")) {
            return "";
        }
        String cellValue = "";
        int cellType = cell.getCellType();
        switch (cellType) {
            case Cell.CELL_TYPE_STRING: 		// 字符串类型
                cellValue = cell.getStringCellValue().trim();
                cellValue = StringUtils.isEmpty(cellValue) ? "" : cellValue;
                break;
            case Cell.CELL_TYPE_BOOLEAN: 		// 布尔类型
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_NUMERIC: 		// 数值类型
                cellValue = new DecimalFormat("#.######").format(cell
                        .getNumericCellValue());
                break;
            default: 						    // 其它类型，取空串吧
                cellValue = "";
                break;
        }
        return cellValue;
    }


    public static void main(String[] args) {
        ResponseEntity<byte[]> down = FileUtil.down("D:\\001\\4.2水的净化.doc", "4.2水的净化.doc");

    }

}
